// import { cloudbaseApp } from './cloudbase-api';
import request from "../utils/request";
import shiJiType from "./shijiType.json";
import { getSgbListVersion } from "./cloudbase-bbkz";
import { setItem, getItem, removeAllItems, getErrorItem, setErrorItem } from "../utils/localStorage";
import { getIsDescendingOrder, sortSgbList } from "@/utils/utils";
import { chaCheRequest } from "@/utils/utils";
import store from "@/store/index";
const SGBDBNAME = process.env.VUE_APP_SGBDBNAME;
const SHIJIDB = process.env.VUE_APP_SHIJIDB;

function tranErrorData(item) {
  // console.log('item.dmturl.pptUrl:', item.dmturl);
  return {
    _id: item.id,
    dmtUrl: {
      adUrl: item.dmturl.adUrl,
      gepuUrl: item.dmturl.gepuUrl,
      pptUrl: item.dmturl.pptUrl,
    },
    isad: item.dmturl.adUrl != "",
    isopern: item.dmturl.gepuUrl != "",
    lyric: item.dmturl.lyric,
    mulu: item.title,
    shijiIndex: item.shiji_index,
    xuhao: item.xuhao,
    years: item.years,
    shijiName: item.shijiname,
    title: item.mulu,
    serial: item.xuhao,
    src: item.dmturl.adUrl,
  };
}

export function tranData(item) {
  return {
    _id: item.id,
    mulu: item.title,
    shijiIndex: item.shiji_index,
    xuhao: item.xuhao,
    years: item.years,
    title: item.mulu,
    serial: item.xuhao,
    isad: item.isad,
  };
}
/**
 * 获取诗集列表
 * @param limit
 * @param page
 * @param filterStr
 * @returns {Promise<GetRes>}
 */
const LOCAL_NEW_VERSION_TOKEN = "NEW_VERSION_TOKEN";
// eslint-disable-next-line no-unused-vars
export async function getSgbItem() {
  try {
    const versionToken = localStorage.getItem(LOCAL_NEW_VERSION_TOKEN);
    const versionData = await getSgbListVersion();
    if (versionToken !== versionData.msg) {
      const reqestData = await request.get(import.meta.env.VITE_SGB_DB_HOST, {
        // 是否添加浏览器指纹
        withCredentials: false,
      });
      const list = await store.dispatch("sgb/getNavJiList");
      const findShijiName = (id) => {
        const res = list.find((it) => it.id == id);
        if (res) return res.name;
      };
      setItem(
        reqestData.rows.map((item) => {
          return {
            ...tranData(item),
            shijiName: findShijiName(item.shiji_index),
          };
        })
      );
      // 根据用户习惯进行排序
      !getIsDescendingOrder() && sortSgbList(getIsDescendingOrder());
      localStorage.setItem(LOCAL_NEW_VERSION_TOKEN, versionData.msg);
    }
    return Promise.resolve({ data: JSON.parse(getItem()) });
  } catch (error) {
    return await getErrorSgbDb();
  }
}

/**
 * 服务器挂掉的情况下，应急使用静态数据。
 * @param {*} params
 * @returns
 */
export async function getErrorSgbDb() {
  const localData = getErrorItem();
  if (localData) {
    return Promise.resolve({ data: JSON.parse(localData) });
  }
  const backData = await import("@/assets/db.json");
  if (backData) {
    setErrorItem(backData.rows.map((item) => tranErrorData(item)));
    return Promise.resolve({ data: JSON.parse(getErrorItem()) });
  }
  return Promise.reject(new Error("获取诗歌列表失败"));
}

export async function getHistoryList() {
  const res = await request.get("/start/zanmei/historyList");
  return res;
}

/**
 * 获取诗集类型
 * @returns {Promise<GetRes>}
 */
export function getShiJiType() {
  return Promise.resolve({
    data: shiJiType,
  });
  // return db.collection(SHIJIDB).get()
}

export async function getErrorItemById(id) {
  const { data } = await getErrorSgbDb();
  return data.find((item) => item._id == id);
}
/**
 * 通过id值查询诗集内容
 */
export async function getShiJiItem(id) {
  try {
    const { data: item } = await request.get(`/start/zanmei/sgb/${id}`);
    return {
      id: item.id,
      _id: item.id,
      dmtUrl: item.dmturl,
      isad: item.dmturl.adUrl != "",
      isopern: item.dmturl.gepuUrl != "",
      lyric: item.dmturl.lyric,
      mulu: item.title,
      shijiIndex: item.shiji_index,
      xuhao: item.xuhao,
      years: item.years,
      shijiName: item.shijiname,
      title: item.title,
      serial: item.xuhao,
      src: item.dmturl.adUrl,
    };
  } catch (error) {
    return await getErrorItemById(id);
  }
}

/**
 * 通过歌词关键查询相关的诗集
 * @param {*} keyword
 * @returns
 */
export async function getShiJiItemByLyric(keyword) {
  if (!keyword) {
    return [];
  }
  const res = await request.get(`/start/zanmei/searchByLryic`, { params: { keyword } });

  return res.data;
}

// /start/shijidb
// 获取诗集类型列表
export function getShiJiList() {
  return request.get("/start/shijidb/list?pageNum=1&pageSize=100&isUpper=1");
}

export function getAllShiJiList() {
  return request.get("/start/shijidb/list?pageNum=1&pageSize=100&isUpper=1");
}

/**
 * 批量查询歌谱
 * @param {*} ids
 * @returns
 */
export async function getShiJiItemGepuUrlByIds(ids) {
  const res = await request.post("/start/zanmei/searchGepuByIds", ids);
  return res.data;
}

export async function requestByidsLazyFields(ids, fields) {
  if (!ids) return [];
  let res;
  try {
    res = await request.get("/start/zanmei/searchByIdsLazyField", {
      params: { ids: ids.join(","), fields: fields.join(",") },
    });
  } catch (error) {
    const promises = ids.map(async (id) => {
      const data = await getErrorItemById(id);
      return {
        ...data?.dmtUrl,
        lyric: data.lyric,
      };
    });
    res = { data: await Promise.all(promises) };
  }

  return res;
}

/**
 * 通过id只获取元数据中必要的字段
 * @param {*} ids
 * @param {*} fields [lyric,lrc,gepuUrl,adUrl,pptUrl]
 * @returns
 */
export async function getShijiItemByidsLazyFields(ids, fields) {
  const res = await chaCheRequest(() => requestByidsLazyFields(ids, fields), {
    key: JSON.stringify(ids),
    time: 1000,
  });
  return res.data;
}
